package com.tlsy.commerce.controller;

import com.tlsy.commerce.shiro.CustomFormAuthenticationFilter;
import com.tlsy.commerce.shiro.CustomPrincipal;
import com.tlsy.commerce.utils.ShiroUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Tlsy
 * @version commerce 0.0.1
 * @date 2017/4/20  17:34
 */
@Controller
public class LoginController extends BaseController {


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginGet(HttpServletRequest request, HttpServletResponse response, Model model) {
        CustomPrincipal principal = ShiroUtil.getCustomPrincipal();

        // 如果已经登录，则跳转到管理首页
        if(principal != null && !principal.isMobileLogin()){
            return REDIRECT_HOME ;
        }

        return "/login";
    }


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String loginPost(HttpServletRequest request, HttpServletResponse response,Model model){
        CustomPrincipal principal = ShiroUtil.getCustomPrincipal();

        // 如果已经登录或者登录成功，则跳转到首页
        if(principal != null){
            return REDIRECT_HOME;
        }

        String username = WebUtils.getCleanParam(request, CustomFormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        boolean rememberMe = WebUtils.isTrue(request, CustomFormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
        boolean mobile = WebUtils.isTrue(request, CustomFormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
        String exception = (String)request.getAttribute(CustomFormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        String message = (String)request.getAttribute(CustomFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

        if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")){
            message = "用户或密码错误, 请重试.";
        }

        model.addAttribute(CustomFormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        model.addAttribute(CustomFormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
        model.addAttribute(CustomFormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
        model.addAttribute(CustomFormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
        model.addAttribute(CustomFormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);


        return "/403";
    }
}
